<template>
    <div class="tableRow">
        <el-row class="select-list" v-permission="'system:post:query'">
            <el-form :inline="true" ref="selectForm" :model="selectFormModel" :label-position="'right'"
                     label-width="80px" size="mini">
                <el-form-item label="岗位名称" prop="postName">
                    <el-input v-model="selectFormModel.postName" placeholder="岗位名称" style="width: 200px" clearable
                              @keyup.enter.native="onSearch"/>
                </el-form-item>
                <el-form-item label="岗位编码" prop="postCode">
                    <el-input v-model="selectFormModel.postCode" placeholder="岗位编码" style="width: 200px" clearable
                              @keyup.enter.native="onSearch"/>
                </el-form-item>
                <el-form-item label="岗位状态" prop="status">
                    <el-select value="" v-model="selectFormModel.status" placeholder="岗位状态" style="width: 200px">
                        <el-option label="正常" value="0"/>
                        <el-option label="停用" value="1"/>
                    </el-select>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" icon="el-icon-search" size="mini" plain round @click="onSearch">搜索
                    </el-button>
                    <el-button type="warning" icon="el-icon-refresh" size="mini" plain round
                               @click="onRefreshSelectForm">重置
                    </el-button>
                </el-form-item>
            </el-form>
        </el-row>
        <el-row class="toolbar">
            <el-button type="primary" icon="el-icon-plus" size="mini" plain @click="handleAdd"
                       v-permission="'system:user:add'">
                新增
            </el-button>
            <el-button type="info" icon="el-icon-edit" :disabled="dialog.isBatchEditDisabled" size="mini" plain
                       @click="handleEdit" v-permission="'system:post:edit'"> 编辑
            </el-button>
            <el-button type="danger" icon="el-icon-delete" :disabled="dialog.isBatchRemoveDisabled" size="mini" plain
                       @click="handleBatchDelete" v-permission="'system:post:remove'"> 删除
            </el-button>
            <el-button type="warning" icon="fa fa-download" size="mini" plain @click="handleExport"
                       v-permission="'system:post:export'"> 导出
            </el-button>
        </el-row>
        <data-table ref="dataTable"
                    :api="getPostList"
                    :options="options"
                    :columns="columns"
                    :operates="operates"
                    :query="selectFormModel"
                    @handleSelectionChange="handleSelectionChange"
        />

        <el-dialog :title="dialog.title"
                   :visible.sync="dialog.dialogFormVisible"
                   :modal-append-to-body="false"
                   :destroy-on-close="false"
                   @close="closeDialog"
                   width="600px">
            <el-form :model="postModel" ref="postForm" label-width="100px" :rules="postFormRules" size="small">
                <el-form-item label="岗位名称" prop="postName">
                    <el-input v-model="postModel.postName" placeholder="岗位名称"/>
                </el-form-item>
                <el-form-item label="岗位编码" prop="postCode">
                    <el-input v-model="postModel.postCode" placeholder="岗位编码"/>
                </el-form-item>
                <el-form-item label="显示排序" prop="orderNum">
                    <el-input-number v-model="postModel.postSort" value="1" :min="1" label="显示顺序"/>
                </el-form-item>
                <el-form-item label="岗位状态">
                    <el-switch v-model="postModel.status" active-color="#13ce66" inactive-color="#ff4949"
                               active-text="正常"
                               inactive-text="停用"
                               active-value="0"
                               inactive-value="1"/>
                </el-form-item>
                <el-form-item label="备注" prop="remark">
                    <el-input v-model="postModel.remark" placeholder="备注" maxlength="100"/>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="dialog.dialogFormVisible=false" size="medium">取 消</el-button>
                <el-button type="primary" @click="submitForm" size="medium">确 定</el-button>
            </div>
        </el-dialog>
    </div>
</template>
<script lang="ts">
    import { Component, Ref, Vue } from 'vue-property-decorator';
    import DataTable from '@/components/DataTable/DataTable.vue';
    import { addPost, checkPostCodeUnique, checkPostNameUnique, exportPost, getPostList, removePost, updatePost } from '@/api/post';
    import { validateForm } from '@/utils';

    @Component({
        components: {
            DataTable
        }
    })
    export default class Post extends Vue {
        @Ref('dataTable') private dataTable: any;
        @Ref('selectForm') private selectForm: any;
        @Ref('postForm') private postForm: any;
        private getPostList: Function = getPostList;

        selectFormModel: any = {
            postName: '',
            postCode: '',
            status: '',
        };
        columns: any = [
            {label: '岗位编号', prop: 'id', sortable: 'custom'},
            {label: '岗位编码', prop: 'postCode', sortable: 'custom'},
            {label: '岗位名称', prop: 'postName', sortable: 'custom'},
            {label: '显示顺序', prop: 'postSort', sortable: 'custom'},
            {
                label: '状态', prop: 'status', sortable: 'custom', render: function (createElement, row) {
                    if (row && row.row && row.row.status === '0') {
                        return createElement('el-tag', {
                                attrs: {
                                    type: 'success'
                                }
                            }, ['正常']
                        );
                    } else if (row && row.row && row.row.status === '1') {
                        return createElement('el-tag', {
                                attrs: {
                                    type: 'warning'
                                }
                            }, ['停用']
                        );
                    } else {
                        return createElement('el-tag', {
                                attrs: {
                                    type: 'danger'
                                }
                            }, ['未知']
                        );
                    }
                }
            },
            {label: '创建时间', prop: 'createTime', sortable: 'custom', width: 160},
            {label: '备注', prop: 'remark', sortable: 'custom'}
        ];
        dialog: any = {
            dialogFormVisible: false,
            title: '对话框',
            isEdit: false,
            isBatchEditDisabled: true,
            isBatchRemoveDisabled: true,
            formData: [],
        };
        postModel: any = {
            postCode: '',
            postName: '',
            postSort: '',
            id: '',
            status: '0',
            remark: ''
        };
        postFormRules: any = {
            postName: [
                {required: true, message: '岗位名称不能为空', trigger: ['blur', 'change']},
                {validator: this.validatePostNameUnique, trigger: 'blur'}
            ],
            postCode: [
                {required: true, message: '岗位编码不能为空', trigger: ['blur', 'change']},
                {validator: this.validatePostCodeUnique, trigger: 'blur'}
            ]
        };
        /*table 的参数*/
        options: any = {
            stripe: true, // 是否为斑马纹 table
            loading: true, // 是否添加表格loading加载动画
            highlightCurrentRow: true, // 是否支持当前行高亮显示
            multipleSelect: true, // 是否支持列表项选中功能
        };
        /*操作栏*/
        operates: any = {
            width: 'auto',
            fixed: 'right',
            list: [
                {
                    label: '编辑',
                    type: 'warning',
                    icon: 'el-icon-edit',
                    plain: true,
                    disabled: (index, row) => {
                        return false;
                    },
                    permission: 'system:post:edit',
                    method: (index, row) => {
                        this.handleEdit(index, row);
                    }
                },
                {
                    label: '删除',
                    type: 'danger',
                    icon: 'el-icon-delete',
                    plain: true,
                    disabled: (index, row) => {
                        return false;
                    },
                    permission: 'system:post:remove',
                    method: (index, row) => {
                        this.handleDelete(index, row);
                    }
                }
            ]
        };

        /*验证岗位名称是否唯一*/
        validatePostNameUnique(rule: any, value: any, callback: any) {
            checkPostNameUnique({
                postName: value,
                id: this.postModel.id
            }).then((res: any) => {
                if (res.data && res.data === '0') {
                    callback();
                } else {
                    callback(new Error('岗位名称已经存在'));
                }
            }).catch((err: any) => {
                console.log(err);
                callback(new Error('岗位名称已经存在'));
            })
        }

        /*验证岗位编码是否唯一*/
        validatePostCodeUnique(rule: any, value: any, callback: any) {
            checkPostCodeUnique({
                postCode: value,
                id: this.postModel.id
            }).then((res: any) => {
                if (res.data && res.data === '0') {
                    callback();
                } else {
                    callback(new Error('岗位编码已经存在'));
                }
            }).catch((err: any) => {
                console.log(err);
                callback(new Error('岗位编码已经存在'));
            })
        }

        /*新增*/
        handleAdd() {
            this.dialog.title = '新增岗位';
            this.dialog.isEdit = false;
            this.dialog.dialogFormVisible = true;
        }

        /*编辑*/
        handleEdit(index: number, row: any) {
            this.postModel = Object.assign({}, row || this.dialog.formData[0]);
            this.dialog.title = '编辑岗位';
            this.dialog.isEdit = true;
            this.dialog.dialogFormVisible = true;
        }

        /*批量删除*/
        handleBatchDelete() {
            //删除
            this.$confirm('确定要删除选定岗位吗？', '警告', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                const ids: Array<any> = [];
                this.dialog.formData.forEach((item, index) => {
                    ids[index] = item.id;
                });
                return removePost({'ids': ids});
            }).then((response: any) => {
                this.dataTable.refresh();
                this.$message.success(response.msg);
            }).catch((e) => {
                console.log(e);
            });
        }

        /*删除*/
        handleDelete(index: number, row: any) {
            this.$confirm('确定要删除该岗位吗？', '警告', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                return removePost({'ids': [row.id]});
            }).then((response: any) => {
                this.dataTable.refresh();
                this.$message.success(response.msg);
            }).catch((e) => {
                console.log(e);
            });
        }

        /*导出excel*/
        handleExport(): void {
            this.$confirm('确定要导出当前查询的所有岗位信息吗？', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'info'
            }).then(() => {
                this.selectFormModel.pageNum = null;
                this.selectFormModel.pageSize = null;
                this.selectFormModel.orderByColumn = 'id';
                this.selectFormModel.isAsc = 'asc';

                return exportPost(this.selectFormModel);
            }).then((response: any) => {
                console.log(response);
                if (response && response.data) {
                    (this as any).$download(response.data.fileName);
                }
            }).catch((e) => {
                console.log(e);
            });
        }

        submitForm(): void {
            this.postForm.validate((valid: boolean) => {
                if (valid) {
                    if (this.dialog.isEdit) {
                        //编辑
                        updatePost(this.postModel).then((response: any) => {
                            this.dataTable.refresh();
                            this.reset();
                            this.dialog.dialogFormVisible = false;
                            this.$message.success(response.msg);
                        }).catch((e) => {
                            console.log(e);
                            validateForm(e.data, this.postForm, this.postFormRules);
                        });
                    } else {
                        //新增
                        addPost(this.postModel).then((response: any) => {
                            this.dataTable.refresh();
                            this.reset();
                            this.dialog.dialogFormVisible = false;
                            this.$message.success(response.msg);
                        }).catch((e) => {
                            console.log(e);
                            validateForm(e.data, this.postForm, this.postFormRules);
                        });
                    }
                }
            });
        }


        /*搜索*/
        onSearch(): void {
            this.dataTable.refresh();
        }

        /*重置*/
        onRefreshSelectForm(): void {
            //恢复搜索默认信息
            this.selectForm.resetFields();
            this.onSearch();
        }

        /*选中事件*/
        handleSelectionChange(val): void {
            if (val) {
                this.dialog.isBatchRemoveDisabled = val.length <= 0;
                this.dialog.isBatchEditDisabled = val.length !== 1;
            }
            this.dialog.formData = val;
        }


        /*重置表单*/
        reset(): void {
            this.postModel = {
                postCode: '',
                postName: '',
                postSort: '',
                id: '',
                status: '0',
                remark: ''
            };
            (this as any).resetForm('postForm');
        }

        /*关闭对话框*/
        closeDialog() {
            this.$nextTick(() => {
                this.reset();
            });
        }
    }
</script>

<style scoped lang="scss">

</style>

